package com.android.tnovoselec.travelassistant.dto;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import android.content.Context;

import com.android.tnovoselec.travelassistant.Config;
import com.google.android.maps.GeoPoint;

public class BenzinskeResultHolder {

    private static GeoPoint LOCATION = null;

    private static List<BenzinskaDto> RESULT = new ArrayList<BenzinskaDto>();

    private BenzinskeResultHolder() {
	super();
    }

    public synchronized static void init(List<BenzinskaDto> benzinske, GeoPoint location, Context context) {
	BenzinskeResultHolder.clear();

	if (benzinske != null) {
	    if (location != null) { // Will always be true (in this application
				    // version)!
		BenzinskeResultHolder.LOCATION = location;
		BenzinskeResultHolder.RESULT = benzinske;
		// ResultHolder.filter(banks, location);
		BenzinskeResultHolder.sort(benzinske, location);
	    }

	    // ResultHolder.group(banks, context);
	}
    }

    public static void filter(List<BenzinskaDto> banks, GeoPoint myLocation) {
	// Not able to do this in query...
	Iterator<BenzinskaDto> bankIterator = banks.iterator();
	while (bankIterator.hasNext()) {
	    BenzinskaDto item = bankIterator.next();
	    if (item.getDistance(myLocation) > Config.RESULT_DISTANCE_LIMIT) {
		// bankIterator.remove();
	    }
	}
    }

    private static void sort(List<BenzinskaDto> banks, final GeoPoint myLocation) {
	Collections.sort(banks, new Comparator<BenzinskaDto>() {

	    @Override
	    public int compare(BenzinskaDto bank1, BenzinskaDto bank2) {
		double distance1 = bank1.getDistance(myLocation);
		double distance2 = bank2.getDistance(myLocation);

		if (distance1 < distance2) {
		    return -1;
		} else if (distance1 > distance2) {
		    return 1;
		}

		return 0;
	    }
	});
    }

    public static List<BenzinskaDto> getAllBenzinske() {
	return new ArrayList<BenzinskaDto>(BenzinskeResultHolder.RESULT);
    }

    public static GeoPoint getMyGeoPoint() {
	return BenzinskeResultHolder.LOCATION;
    }

    public static void clear() {
	// TODO Recycle loaded bitmaps if necessary..

	BenzinskeResultHolder.RESULT.clear();
	BenzinskeResultHolder.LOCATION = null;
    }

}
